#coding=utf-8
'''
Created on 2017-7-15

@author: sandy
'''
import logging

class HallInfoManager(object):
    
    def __init__(self):
        self.infomap = {}
        self.infomap_hiden = {}
    
    def update(self, sid, sip, sport, hallinfos):
        logging.info(u"HallInfoManager update, sid=%d", sid)
        d = {}
        d[u"sid"] = sid
        d[u"sip"] = sip
        d[u"sport"] = sport
        d[u"hallinfo"] = hallinfos
        
        if self.infomap_hiden.get(sid)!=None:
            self.infomap_hiden[sid] = d
        else:
            self.infomap[sid] = d
        
    def remove(self, sid):
        logging.info(u"HallInfoManager remove, sid=%d", sid)
        if self.infomap_hiden.get(sid)!=None:
            self.infomap_hiden.pop(sid, None)
        else:
            self.infomap.pop(sid, None)
        
    def getAllHallInfo(self):
        return self.infomap  
    
    def hideGs(self, sid, hide):
        if hide:
            d = self.infomap.pop(sid)       
            self.infomap_hiden[sid] = d
        else:
            d = self.infomap_hiden.pop(sid)       
            self.infomap[sid] = d

    def getHallsByMatchNum(self,matchNum):
        ds = []
        for key in self.infomap:
            d = self.infomap.get(key)
            hallinfos = d.get("hallinfo")
            for i in range(len(hallinfos)):
                info = hallinfos[i]
                t = {}
                if info.get("matchNum") == matchNum:
                    t['sid'] = key
                    t['hid'] = info.get("id")
                    t['precent'] = info.get('usetable') / info.get('maxtable')
                    ds.append(t)
        return ds

    def tickUpdateHall(self,sid,result):
        d = self.infomap.get(sid)
        hallinfos = d.get("hallinfo")
        logging.debug("before tickUpdateHall %s",hallinfos)
        for hall in hallinfos:
            hid = hall.get('id')
            if hid in result:
                hall['usetable'] = result.get(hid)
            else:
                logging.debug("sid=%d hid=%d not report",sid,hid)
        logging.debug("after tickUpdateHall %s",hallinfos)
        pass

    def choseSuitableGameAndHallId(self,tableModel):
        res = self.getHallsByMatchNum(tableModel)
        suit = None
        if len(res) != 0:
            minPrecent = 1
            for re in res:
                if re.get("precent") < minPrecent:
                    suit = re
                    minPrecent = re.get("precent")
        return suit

instance = HallInfoManager()

if __name__ == '__main__':
    pass